package com.lwz.android.image;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import ru.truba.touchgallery.TouchView.InputStreamWrapper;
import ru.truba.touchgallery.TouchView.InputStreamWrapper.InputStreamProgressListener;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.loopj.android.image.SmartImage;
import com.loopj.android.image.WebImageCache;

public class ProgressWebImage implements SmartImage {

	private static final int CONNECT_TIMEOUT = 5000;
    private static final int READ_TIMEOUT = 10000;

    private static WebImageCache webImageCache;

    private String url;

    public ProgressWebImage(String url) {
        this.url = url;
    }

    public Bitmap getBitmap(Context context) {
        // Don't leak context
        if(webImageCache == null) {
            webImageCache = new WebImageCache(context);
        }

        // Try getting bitmap from cache first
        Bitmap bitmap = null;
        if(url != null) {
            bitmap = webImageCache.get(url);
            if(bitmap == null) {
                bitmap = getBitmapFromUrl(url);
                if(bitmap != null){
                    webImageCache.put(url, bitmap);
                }
            }
        }
        return bitmap;
    }

    private Bitmap getBitmapFromUrl(String url) {
        Bitmap bitmap = null;

        try {
            URLConnection conn = new URL(url).openConnection();
            conn.setConnectTimeout(CONNECT_TIMEOUT);
            conn.setReadTimeout(READ_TIMEOUT);
            InputStream is = conn.getInputStream();
            int totalLen = conn.getContentLength();
            InputStreamWrapper bis = new InputStreamWrapper(is, 8192, totalLen);
            if( mInputStreamProgressListener != null ) {
            	bis.setProgressListener(mInputStreamProgressListener);
            }
            bitmap = BitmapFactory.decodeStream(bis);
            bis.close();
            is.close();
        } catch(Exception e) {
            e.printStackTrace();
        }

        return bitmap;
    }
    
    private InputStreamProgressListener mInputStreamProgressListener;
    
    public void setOnProgressListener(InputStreamProgressListener l) {
    	mInputStreamProgressListener = l;
    }

    public static void removeFromCache(String url) {
        if(webImageCache != null) {
            webImageCache.remove(url);
        }
    }

	
}
